﻿using System;
using System.ComponentModel.Composition;
using MyMusicPlayer.Applications.ViewModels;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using MyMusicPlayer.Utils;
using MyMusicPlayer.Domain;
using System.Collections.ObjectModel;
using MyMusicPlayer.Applications.Services;
using MyMusicPlayer.Presentation.Views;
using System.IO;

namespace MyMusicPlayer.Applications.Controllers
{
    [Export]
    internal class PlaylistController
    {
        private readonly IShellService shellService;

        private PlaylistViewModel playlistViewModel;

        private readonly DelegateCommand likeCommand;   // 喜好按钮。添加选中的音乐到喜好列表中。
        private readonly DelegateCommand removeCommand; // 从播放列表中移除
        private readonly DelegateCommand mouseDoubleClick;      // 鼠标双击：选中并播放音乐
        private readonly DelegateCommand playMusicRightClick;   // 右键菜单：播放音乐
        private readonly DelegateCommand openFileRightClick;    // 右键菜单：打开文件所在目录
        private readonly DelegateCommand deleteMusicRightClick; // 右键菜单：删除一首歌
        private readonly DelegateCommand deleteAllRightClick;   // 右键菜单：清空播放列表

        public Action<MusicInfo> PlayMusicAction;   // 播放音乐
        public MusicInfo currMusic;         // 当前正在播放中的音乐
        //public bool isPlaying = false;    // 是否正在播放中
        public bool isMusicEnd = false;     // 当前正在播放中的音乐是否整首歌播放完了
        private PlaylistView playlistView;


        [ImportingConstructor]
        public PlaylistController(IShellService shellService, PlaylistViewModel playlistViewModel)
        {
            this.shellService = shellService;
            this.playlistViewModel = playlistViewModel;
            likeCommand = new DelegateCommand(p => LikeCommand((Button)p));
            removeCommand = new DelegateCommand(p => RemoveCommand((Button)p));
            mouseDoubleClick = new DelegateCommand(p => MouseDoubleClick((object)p));
            playMusicRightClick = new DelegateCommand(p => PlayMusicRightClick((object)p));
            openFileRightClick = new DelegateCommand(p => OpenFileRightClick((object)p));
            deleteMusicRightClick = new DelegateCommand(p => DeleteMusicRightClick((object)p));
            deleteAllRightClick = new DelegateCommand(p => DeleteAllRightClick((object)p));
        }


        public void Initialize()
        {
            shellService.PlaylistView = playlistViewModel.View;
            playlistView = playlistViewModel.View as PlaylistView;
            playlistViewModel.LikeCommand = likeCommand;
            playlistViewModel.RemoveCommand = removeCommand;
            playlistViewModel.MouseDoubleClick = mouseDoubleClick;
            playlistViewModel.PlayMusicRightClick = playMusicRightClick;
            playlistViewModel.OpenFileRightClick = openFileRightClick;
            playlistViewModel.DeleteMusicRightClick = deleteMusicRightClick;
            playlistViewModel.DeleteAllRightClick = deleteAllRightClick;

            // 初始化配置文件
            XMLHelper.CreatePlaylistFile();
            // 播放列表数据回显
            InitPlaylist();
        }


        /// <summary>
        /// 打开软件时，播放列表数据回显。从XML配置文件中获取数据。
        /// </summary>
        private void InitPlaylist()
        {
            var temp = XMLHelper.GetAllMusicInfoCache();
            playlistViewModel.MusicList.Clear();
            for (int i = 0; i < temp.Count; i++)
            {
                var item = temp[i];
                item.Index = i + 1;
                playlistViewModel.MusicList.Add(item);
            }
        }


        /// <summary>
        /// 喜好按钮。添加选中的音乐到喜好列表中。
        /// </summary>
        private void LikeCommand(Button btn)
        {
            MessageBox.Show("添加到喜好列表中");
        }


        private void RemoveCommand(Button btn)
        {
            MessageBoxResult result = MessageBox.Show("从播放列表中删除？", "移除音乐", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                MusicInfo musicInfo = (MusicInfo)btn.DataContext;
                RemoveItem(musicInfo);
            }
        }


        /// <summary>
        /// 从播放列表中移除。更新UI和本地库。
        /// </summary>
        /// <param name="musicInfo"></param>
        public void RemoveItem(MusicInfo musicInfo)
        {
            // 从列表中移除Item
            var index = 0;
            for (int i = 0; i < playlistViewModel.MusicList.Count; i++)
            {
                var item = playlistViewModel.MusicList[i];
                if (item.Id.Equals(musicInfo.Id))
                {
                    playlistViewModel.MusicList.Remove(item);
                    // 记录被移除的元素角标，之后的所有元素的Id往前移一位
                    index = i;
                    break;
                }
            }
            for (int i = 0; i < playlistViewModel.MusicList.Count; i++)
            {
                var item = playlistViewModel.MusicList[i];
                if (i >= index)
                {
                    item.Index -= 1;
                }
            }

            // 还要修改UI层，否则UI与数据层不一致！
            playlistViewModel.SetMultiMusicInfoIndexByDeleteItem(musicInfo);
            // 本地数据库（配置文件）中移除元素
            XMLHelper.RemoveMusicInfoItem(musicInfo);
        }


        /// <summary>
        /// 鼠标双击：选中并播放音乐
        /// </summary>
        /// <param name="p"></param>
        private void MouseDoubleClick(object p)
        {
            ListViewItem listViewItem = (ListViewItem)p;
            MusicInfo selectedMusic = (MusicInfo)listViewItem.DataContext;
            if (currMusic == null || !currMusic.Id.Equals(selectedMusic.Id))
            {
                PlayMusicAction?.Invoke(selectedMusic);
            }
        }


        /// <summary>
        /// 右键菜单：播放音乐
        /// </summary>
        /// <param name="p"></param>
        private void PlayMusicRightClick(object p)
        {
            MusicInfo selectedMusic = (MusicInfo)playlistView.playList.SelectedValue;
            if (currMusic == null || !currMusic.Id.Equals(selectedMusic.Id))
            {
                PlayMusicAction?.Invoke(selectedMusic);
            }
        }


        /// <summary>
        /// 右键菜单：打开文件所在目录
        /// </summary>
        /// <param name="p"></param>
        private void OpenFileRightClick(object p)
        {
            MusicInfo selectedMusic = (MusicInfo)playlistView.playList.SelectedValue;
            if (!File.Exists(selectedMusic.FullPath))
            {
                MessageBox.Show("源文件已被移除了！");
                // 刷新播放列表，移除该音乐。
                RemoveItem(selectedMusic);
                return;
            }
            FileInfo fi = new FileInfo(selectedMusic.FullPath);
            System.Diagnostics.Process.Start("Explorer", "/select," + fi.FullName);
        }


        /// <summary>
        /// 右键菜单：删除一首歌
        /// </summary>
        /// <param name="p"></param>
        private void DeleteMusicRightClick(object p)
        {
            MessageBoxResult result = MessageBox.Show("从播放列表中删除？", "移除音乐", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                MusicInfo selectedMusic = (MusicInfo)playlistView.playList.SelectedValue;
                RemoveItem(selectedMusic);
            }
        }


        /// <summary>
        /// 右键菜单：清空列表
        /// </summary>
        /// <param name="p"></param>
        private void DeleteAllRightClick(object p)
        {
            MessageBoxResult result = MessageBox.Show("清空播放列表！？", "注意咯", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                // 清空数据层
                playlistViewModel.MusicList.Clear();
                // 清空本地库
                XMLHelper.RemoveAllMusicInfoItem();
            }
        }

    }
}
